/*************************************************************************
	> File Name: clone.c
	> Author: Angel Criss
	> Mail: abbytsing@gmail.com 
	> Created Time: 2014年07月16日 星期三 17时00分04秒
 ************************************************************************/
// man clone, man 2 unshare

#include"head.h"
#include<sched.h>
#include<fcntl.h>

int childfunc(void *arg)
{
    if(close(*((int *)arg))==-1)
        err("close");
    return 0;
}

int main(int argc, char *argv[])
{
    void *stack_bottom;
    void *stack_top;
    int fd,status,flag;

    if((fd=open("test.txt",O_CREAT|O_RDWR,00644))==-1)
            err("open");

    flag=(argc>1)?CLONE_FILES:0; 

    stack_bottom=malloc(65536); // 从堆上 开辟 65536 大小空间(向上)
    if(stack_bottom==NULL)
        err("malloc");

    stack_top=stack_bottom+65536; // 栈向下长到 65536 （栈顶)

    if(clone(childfunc,stack_top,flag,(void *)&fd)==-1)
        err("clone");

    if(waitpid(-1,&status,WUNTRACED|__WCLONE)==-1)  // have to use __WCLONE
        err("waitpid");
    p_wait_status(NULL,status);

    if(write(fd,"test",4)==-1)
        printf("cannot wrtite, fd closed\n");
    else
        printf("write succeed\n");
    exit(EXIT_SUCCESS);

}
